package com.pratices.mvc.servlet.common;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.pratices.mvc.util.JsonUtil;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class CommonServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp){
        dispatch(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp){
        dispatch(req, resp);
    }
    private void dispatch(HttpServletRequest req, HttpServletResponse resp){
        //通过反射获取方法，再去执行方法
           //1.获取方法名字
        String requestURI = req.getRequestURI();
        String methodName = requestURI.substring(requestURI.lastIndexOf("/") + 1);
           //2.获取方法
        try {
            Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
           //3.执行方法
            method.setAccessible(true);
            Object result = method.invoke(this, req, resp);
            resp.setContentType("application/json;charset=utf-8");
            String json = JsonUtil.toJson(result);
            resp.getWriter().println(json);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
